//
//  GatewaySharedController.m
//  YSSmartHome
//
//  Created by yanghao on 2016/10/8.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "GatewaySharedController.h"
#import "XAIGateway.h"
#import "UIView+Frame.h"
#import "UIView+HUD.h"
#import <Photos/Photos.h>
#import "GlobalConst.h"
#import "QrCodeUtils.h"

@interface GatewaySharedController ()

@property (nonatomic, strong)UIImageView  *topLine;
@property (nonatomic, strong)UIImageView  *bottomLine;
@property (nonatomic, strong)UILabel      *titleLabel;
@property (nonatomic, strong)UILabel      *detailLabel;
@property (nonatomic, strong)UIImageView  *qrCodeView;
@property (nonatomic, strong)UILabel      *tipsLabel;
@property (nonatomic, strong)UIView       *contentView;
@end

@implementation GatewaySharedController


#pragma mark - life cycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initSubViews];
    [self sharedGateway];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - private method
- (void)initSubViews
{
    [self initNavigationView];
    [self.view addSubview:self.contentView];
    [self.contentView addSubview:self.topLine];
    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.detailLabel];
    [self.contentView addSubview:self.qrCodeView];
    [self.contentView addSubview:self.tipsLabel];
    [self.contentView addSubview:self.bottomLine];
    [self layoutPageSubviews];
}
- (void)initNavigationView
{
    self.navigationItem.title = @"网关分享";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存图片" style:UIBarButtonItemStyleDone target:self action:@selector(savePicture) ];
}
- (void)layoutPageSubviews
{
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.leading.equalTo(self.view).offset(kIphoneSize_Widith(30));
        make.trailing.equalTo(self.view).offset(kIphoneSize_Widith(-30));
        make.height.equalTo(kIphoneSize_Height(400));
    }];
    [self.topLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(self.contentView);
        make.height.equalTo(kIphoneSize_Height(10));
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.contentView);
        make.top.equalTo(self.topLine.bottom).offset(kIphoneSize_Height(25));
    }];
    [self.detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.contentView);
        make.top.equalTo(self.titleLabel.bottom).offset(kIphoneSize_Height(5));
    }];
    [self.qrCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.contentView);
        make.top.equalTo(self.detailLabel.bottom).offset(kIphoneSize_Height(20));
        make.leading.equalTo(self.contentView).offset(kIphoneSize_Widith(40));
        make.trailing.equalTo(self.contentView).offset(kIphoneSize_Widith(-40));
        make.height.equalTo(kIphoneSize_Height(250));
    }];
    [self.tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.contentView);
        make.top.equalTo(self.qrCodeView.bottom).offset(kIphoneSize_Height(10));
    }];
    [self.bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.contentView);
        make.height.equalTo(kIphoneSize_Height(10));
    }];
}

-(uint32_t)getRandomNumber:(uint32_t)from to:(uint32_t)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
}

- (void)sharedGateway
{
    XAITYPEAPSN apsn = kMQTTSessionManager.currentGateway.apsn;
    uint32_t num = [self getRandomNumber:100000 to:1000000];
    NSString *apsnStr = [NSString stringWithFormat:@"%08x,%zd",apsn,num];
    self.qrCodeView.image = [QrCodeUtils generateQrCodeImage:apsnStr withSize:200];
}

- (void)savePicture
{
    PHAuthorizationStatus photoAuthStatus = [PHPhotoLibrary authorizationStatus];
    if (photoAuthStatus == PHAuthorizationStatusNotDetermined)
    {// 未询问是否授权 可以用下面的请求授权方法询问用户
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized)
            {
                // 用户同意授权
                UIImage *image = [self makeImageWithView:self.contentView withSize:self.contentView.yh_size];
                [self saveImageToPhotos:image];
            }else {
                // 用户拒绝授权
                [self.view yh_showMsgHUD: @"图片保存失败"];
            }
        }];
    }
    else if(photoAuthStatus == PHAuthorizationStatusRestricted || photoAuthStatus == PHAuthorizationStatusDenied) {// 未授权
        UIAlertView* alerView = [[UIAlertView alloc]initWithTitle:@"相册权限未开启" message:@"相册权限未开启，请进入系统【设置】>【隐私】>【相册】中打开开关,开启相册功能" delegate:self cancelButtonTitle:@"好" otherButtonTitles:@"设置", nil];
        [alerView show];
    }
    else // 已授权
    {
        UIImage *image = [self makeImageWithView:self.contentView withSize:self.contentView.yh_size];
        [self saveImageToPhotos:image];
    }

}

- (void)saveImageToPhotos:(UIImage*)savedImage
{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex NS_DEPRECATED_IOS(2_0, 9_0)
{
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
    
}

// 指定回调方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *msg = nil ;
    if(error != NULL) {
        msg = @"保存图片失败" ;
        [self.view yh_showMsgHUD:msg];
    } else {
        msg = @"保存图片成功" ;
        [self.view yh_showMsgHUD:msg];
    }
}

- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size {
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

#pragma mark - getters and setters
- (UIView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIView alloc]init];
        _contentView.backgroundColor = [UIColor whiteColor];
    }
    return _contentView;
}
- (UIImageView *)topLine
{
    if (!_topLine) {
        _topLine = [[UIImageView alloc]init];
        _topLine.image = [UIImage imageNamed:@"me_shared_line"];
    }
    return _topLine;
}
- (UIImageView *)bottomLine
{
    if (!_bottomLine) {
        _bottomLine = [[UIImageView alloc]init];
        _bottomLine.image = [UIImage imageNamed:@"me_shared_line"];
    }
    return _bottomLine;
}


- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.text = @"扫一扫让你的亲朋好友";
        _tipsLabel.textColor = RGBColor(51, 51, 51);
        _titleLabel.font = [UIFont systemFontOfSize:18];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}
- (UILabel *)detailLabel
{
    if (!_detailLabel) {
        _detailLabel = [[UILabel alloc]init];
        _detailLabel.text = @"快速添加网关，共享智能生活";
        _detailLabel.textColor = RGBColor(102, 102, 102);
        _detailLabel.font = [UIFont systemFontOfSize:16];
        _detailLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _detailLabel;
}

- (UIImageView *)qrCodeView
{
    if (!_qrCodeView) {
        _qrCodeView = [[UIImageView alloc]init];
    }
    return _qrCodeView;
}
- (UILabel *)tipsLabel
{
    if (!_tipsLabel) {
        _tipsLabel = [[UILabel alloc]init];
        _tipsLabel.text = @"扫一扫上面的二维码图案添,加设备网关";
        _tipsLabel.font = [UIFont systemFontOfSize:13];
        _tipsLabel.textColor = RGBColor(153, 153, 153);
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _tipsLabel;
}
@end
